import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:ebuy/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../data_source/data_source.dart';
import '../../dio/dio_helper/api.dart';
import '../model/cart_product_model.dart';
import '../utils/CustomTextStyle.dart';
import '../utils/CustomUtils.dart';
import '../widgets/app_search_bar.dart';
import 'CheckOutPage.dart';
import 'CustomApply.dart';
import '../controller.dart';

class CartPage extends StatefulWidget {
  @override
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('购物车'),
        actions: [
          TextButton(
              onPressed: () async {
                /// 4单证传输
                try {
                  List res = await Api.saveApplyService('DZYW2024062300043');
                  Toast.show('返回结果: $res');
                } catch (e) {
                  print(e);
                }
              },
              child: Text('上传'))
        ],
      ),
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.grey.shade100,
      body: Builder(
        builder: (context) {
          return ListView(
            children: <Widget>[
              searchBar(),
              createHeader(),
              createCartList(),
              footer(context)
            ],
          );
        },
      ),
    );
  }

  searchBar() {
    return Row(
      children: [
        SizedBox(width: 120, child: dropDown()),
        Expanded(child: AppSearchBar()),
        SizedBox(
          height: 40,
          width: 100,
          child: ElevatedButton(
            onPressed: () async {
              if (selectedValue == '订单单号') {
                /// 3出口业务查询接口
                try {
                  var res = await Api.getApplyService('DZYW2024062300043');
                  Toast.show('返回结果: ${res.toString()}');
                } catch (e) {
                  print(e);
                }
              } else {
                /// 6出口业务轨迹查询接口
                try {
                  var res = await Api.getWaybillInfo('DZYW2024062300043');
                  Toast.show('返回结果: ${res.toString()}');
                } catch (e) {
                  print(e);
                }
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.green,
              // 按钮背景颜色
              // padding: EdgeInsets.only(top: 12, left: 60, right: 60, bottom: 12), // 按钮内边距
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(24)),
              ),
            ),
            child: Text(
              "查询",
              style: CustomTextStyle.textFormFieldSemiBold
                  .copyWith(color: Colors.white),
            ),
          ),
        ),
      ],
    );
  }

  String selectedValue = '订单单号';

  dropDown() {
    return DropdownButtonHideUnderline(
      child: DropdownButton2<String>(
        isExpanded: true,
        hint: Text(
          '单号',
          style: TextStyle(
            fontSize: 14,
            color: Theme.of(context).hintColor,
          ),
        ),
        items: ['订单单号', '物流单号']
            .map((String item) => DropdownMenuItem<String>(
                  value: item,
                  child: Text(
                    item,
                    style: const TextStyle(
                      fontSize: 14,
                    ),
                  ),
                ))
            .toList(),
        value: selectedValue,
        onChanged: (String? value) {
          if (value != null) {
            setState(() {
              selectedValue = value;
            });
          }
        },
        buttonStyleData: const ButtonStyleData(
          padding: EdgeInsets.symmetric(horizontal: 16),
          height: 40,
          width: 140,
        ),
        menuItemStyleData: const MenuItemStyleData(
          height: 40,
        ),
      ),
    );
  }

  footer(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //   children: <Widget>[
          //     Container(
          //       margin: EdgeInsets.only(left: 30),
          //       child: Text(
          //         "Total",
          //         style: CustomTextStyle.textFormFieldMedium.copyWith(color: Colors.grey, fontSize: 12),
          //       ),
          //     ),
          //     Container(
          //       margin: EdgeInsets.only(right: 30),
          //       child: Text(
          //         "\$299.00",
          //         style: CustomTextStyle.textFormFieldBlack.copyWith(color: Colors.greenAccent.shade700, fontSize: 14),
          //       ),
          //     ),
          //   ],
          // ),
          // Utils.getSizedBox(height: 8),
          ElevatedButton(
            onPressed: () async {
              /// 2出口业务接入
              try {
                Map res = await Api.applyService(applyServiceData);
                Toast.show('返回结果: $res');
              } catch (e) {
                print(e);
              }
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(builder: (context) => CheckOutPage()),
              // );
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.green, // 按钮背景颜色
              padding: EdgeInsets.only(
                  top: 12, left: 60, right: 60, bottom: 12), // 按钮内边距
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(24)),
              ),
            ),
            child: Text(
              "Checkout",
              style: CustomTextStyle.textFormFieldSemiBold
                  .copyWith(color: Colors.white),
            ),
          ),
          Utils.getSizedBox(height: 8),
        ],
      ),
    );
  }

  createHeader() {
    return Container(
      alignment: Alignment.topLeft,
      child: Text(
        "SHOPPING CART",
        style: CustomTextStyle.textFormFieldBold
            .copyWith(fontSize: 16, color: Colors.black),
      ),
      margin: EdgeInsets.only(left: 12, top: 12),
    );
  }

  // createSubTitle() {
  //   return Container(
  //     alignment: Alignment.topLeft,
  //     child: Text(
  //       "Total(3) Items",
  //       style: CustomTextStyle.textFormFieldBold.copyWith(fontSize: 12, color: Colors.grey),
  //     ),
  //     margin: EdgeInsets.only(left: 12, top: 4),
  //   );
  // }

  CartController cartController = Get.find<CartController>();

  createCartList() {
    return Obx(() => ListView.builder(
          shrinkWrap: true,
          primary: false,
          itemBuilder: (context, index) {
            return createCartListItem(index);
          },
          itemCount: cartController.products.length,
        ));
  }

  createCartListItem(int index) {
    CartProductModel productItem = cartController.products[index];
    return Stack(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(left: 16, right: 16, top: 16),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(16))),
          child: Row(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(right: 8, left: 8, top: 8, bottom: 8),
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(14)),
                    color: Colors.blue.shade200,
                    image:
                        DecorationImage(image: AssetImage(productItem.image!))),
              ),
              Expanded(
                flex: 100,
                child: Container(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.only(right: 8, top: 4),
                        child: Text(
                          productItem.name!,
                          maxLines: 2,
                          softWrap: true,
                          style: CustomTextStyle.textFormFieldSemiBold
                              .copyWith(fontSize: 14),
                        ),
                      ),
                      Utils.getSizedBox(height: 6),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            productItem.type!,
                            style: CustomTextStyle.textFormFieldRegular
                                .copyWith(color: Colors.grey, fontSize: 14),
                          ),
                          GestureDetector(
                            onTap: () {
                              Get.to(CustomApply());
                            },
                            child: Text(
                              '海关申请',
                              style: CustomTextStyle.textFormFieldRegular
                                  .copyWith(color: Colors.grey, fontSize: 14),
                            ),
                          )
                        ],
                      ),
                      Container(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Text(
                              productItem.price!,
                              style: CustomTextStyle.textFormFieldBlack
                                  .copyWith(color: Colors.green),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: <Widget>[
                                  GestureDetector(
                                    onTap: () {},
                                    child: Icon(
                                      Icons.remove,
                                      size: 24,
                                      color: Colors.grey.shade700,
                                    ),
                                  ),
                                  Container(
                                    color: Colors.grey.shade200,
                                    padding: const EdgeInsets.only(
                                        bottom: 2, right: 12, left: 12),
                                    child: Text(
                                      productItem.count.toString(),
                                      style:
                                          CustomTextStyle.textFormFieldSemiBold,
                                    ),
                                  ),
                                  Icon(
                                    Icons.add,
                                    size: 24,
                                    color: Colors.grey.shade700,
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        Align(
          alignment: Alignment.topRight,
          child: Container(
            width: 24,
            height: 24,
            alignment: Alignment.center,
            margin: EdgeInsets.only(right: 10, top: 8),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(4)),
                color: Colors.green),
            child: GestureDetector(
              onTap: () {
                cartController.products.removeLast();
                cartController.products.refresh();
              },
              child: const Icon(
                Icons.close,
                color: Colors.white,
                size: 20,
              ),
            ),
          ),
        )
      ],
    );
  }
}
